package com.controller.news;

import com.entity.News;
import com.util.DataSourceUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

@WebServlet("/content")
public class GetNewsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sql = "select * from news where id=?";
        News news = null;
        try (Connection conn = DataSourceUtils.getConnection();
             PreparedStatement st = conn.prepareStatement(sql)) {
            st.setString(1, req.getParameter("nid"));
            try (ResultSet rs = st.executeQuery()) {
                while (rs.next()) {
                    int id = rs.getInt("id");
                    String title = rs.getString("title");
                    Date addTime = rs.getDate("addtime");
                    String type = rs.getString("type");
                    String content = rs.getString("content");
                    news = new News(id, title, type, content, addTime);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        req.setAttribute("news", news);
        req.getRequestDispatcher("/WEB-INF/news/news.jsp").forward(req, resp);
    }
}
